//
//  UILabel+Extension.swift
//  CosClub
//
//  Created by 沙睿 on 2020/2/7.
//  Copyright © 2020 ios. All rights reserved.
//

import Foundation
import UIKit

extension UILabel {
     
    public func setStyle(color: UIColor = UIColor.app.c3a, fontSize: CGFloat, type:FontType = FontType.nomal) -> Void
    {
        self.textColor = color
        
        switch type {
        case .nomal:
            self.font = UIFont.sr_system(fontSize: fontSize)
        case .bold:
            self.font = UIFont.sr_bold(fontSize: fontSize)
        case .number:
            self.font = UIFont.sr_number(fontSize: fontSize)
        }
    }
    
    public convenience init(_ text: String? = "", color: UIColor = UIColor.app.c3a, fontSize: CGFloat, type:FontType = FontType.nomal)
    {
        self.init()
        self.text = text
        self.setStyle(color: color, fontSize: fontSize, type: type)
    }
    
    /// 设置行间距
    public var lineSpacing: CGFloat {
        set {
            let paraph = NSMutableParagraphStyle()
            paraph.lineSpacing = newValue
            let attributes = [NSAttributedString.Key.font:UIFont.systemFont(ofSize: self.font.pointSize),
                              NSAttributedString.Key.paragraphStyle: paraph]
            self.attributedText = NSAttributedString(string: self.text ?? "", attributes: attributes)
        } get { 0 }
    }
    
    /// 获取自适应高度
    public func sizeToFitWidth() {
        let height = self.height
        self.sizeToFit()
        self.height = height
    }
}

extension UILabel {
    
    /// 判断文本标签的内容是否被截断
    public var isTruncated: Bool {
        guard let labelText = text else {
            return false
        }
         
        //计算理论上显示所有文字需要的尺寸
        let rect = CGSize(width: self.bounds.width, height: CGFloat.greatestFiniteMagnitude)
        let labelTextSize = (labelText as NSString)
            .boundingRect(with: rect, options: .usesLineFragmentOrigin,
                          attributes: [NSAttributedString.Key.font: self.font!], context: nil)
         
        //计算理论上需要的行数
        let labelTextLines = Int(ceil(CGFloat(labelTextSize.height) / self.font.lineHeight))
         
        //实际可显示的行数
        var labelShowLines = Int(floor(CGFloat(bounds.size.height) / self.font.lineHeight))
        if self.numberOfLines != 0 {
            labelShowLines = min(labelShowLines, self.numberOfLines)
        }
         
        //比较两个行数来判断是否需要截断
        return labelTextLines > labelShowLines
    }
}




